<template>
  <el-form label-width="100px">
    <el-form-item label="spu名称">
      <el-input
        placeholder="请输入spu名称"
        v-model="spuParams.spuName"
      ></el-input>
    </el-form-item>
    <el-form-item label="spu品牌">
      <el-select v-model="spuParams.tmId">
        <el-option
          v-for="item in allTradeMark"
          :key="item.id"
          :label="item.tmName"
          :value="item.id"
        ></el-option>
      </el-select>
    </el-form-item>
    <el-form-item label="spu描述">
      <el-input
        type="textarea"
        :rows="3"
        placeholder="请输入spu名称"
        v-model="spuParams.description"
      ></el-input>
    </el-form-item>
    <el-form-item label="spu图片">
      <el-upload
        v-model:file-list="imgList"
        action="/api/admin/product/fileUpload"
        list-type="picture-card"
        :on-preview="handlePictureCardPreview"
        :on-remove="handleRemove"
        :before-upload="handlerUpload"
      >
        <el-icon>
          <Plus />
        </el-icon>
      </el-upload>
      <el-dialog v-model="dialogVisible">
        <img
          w-full
          :src="dialogImageUrl"
          alt="Preview Image"
          style="width: 100%; height: 100%"
        />
      </el-dialog>
    </el-form-item>
    <el-form-item label="spu销售属性">
      <el-select v-model="saleAttrIdAndValueName">
        <el-option
          v-for="item in unSelectSaleAttr"
          :key="item.id"
          :label="item.name"
          :value="`${item.id}:${item.name}`"
        ></el-option>
      </el-select>
      <el-button
        @click="addSaleAttr"
        :disabled="!saleAttrIdAndValueName"
        style="margin-left: 20px"
        type="primary"
        icon="Plus"
      >
        添加属性
      </el-button>
      <el-table :data="saleAttr" style="margin: 10px 0" border>
        <el-table-column type="index" label="序号" width="80"></el-table-column>
        <el-table-column
          label="销售属性名"
          prop="saleAttrName"
          width="100"
        ></el-table-column>
        <el-table-column prop="prop" label="属性值">
          <template #="{ row }">
            <div class="flex gap-2">
              <el-tag
                style="margin: 0 5px"
                @close="row.spuSaleAttrValueList.splice(index, 1)"
                v-for="(tag, index) in row.spuSaleAttrValueList"
                :key="tag.id"
                closable
              >
                {{ tag.saleAttrValueName }}
              </el-tag>
              <el-input
                @blur="toLook(row)"
                v-model="row.saleAttrValue"
                v-if="row.flag == true"
                placeholder="请你输入属性值"
                size="small"
                style="width: 100px"
              ></el-input>
              <el-button
                @click="toEdit(row)"
                v-else
                type="success"
                size="small"
                icon="Plus"
              ></el-button>
            </div>
          </template>
        </el-table-column>
        <el-table-column align="center" label="操作">
          <template #="{ $index }">
            <el-button
              type="danger"
              size="small"
              icon="Delete"
              @click="saleAttr.splice($index, 1)"
            ></el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="save">保存</el-button>
      <el-button @click="cancel">取消</el-button>
    </el-form-item>
  </el-form>
</template>

<script lang="ts" setup>
import { ref, reactive, computed } from 'vue'
import type {
  SaleAttrValue,
  Spu,
  SpuImg,
  SaleAttr,
  HasSaleAttr,
  AllTradeMark,
  SpuHasImg,
  SaleAttrResponseData,
  HasSaleAttrResponseData,
  trademark,
} from '@/api/product/spu/types'
import {
  reqAllTradeMark,
  reqSpuImageList,
  reqSpuHasSaleAttr,
  reqAllSaleAttr,
  reqAddOrUpdateSpu,
} from '@/api/product/spu'
import { ElMessage } from 'element-plus'

let $emit = defineEmits(['changeScene'])
let dialogVisible = ref(false)
let dialogImageUrl = ref('')
let saleAttrIdAndValueName = ref('')

function cancel() {
  $emit('changeScene', 0)
}

let allTradeMark = ref<trademark[]>()
let imgList = ref<SpuImg[]>([])
// 已有Spu销售属性
let saleAttr = ref<SaleAttr[]>([])
let allSaleAttr = ref<HasSaleAttr[]>([])
let spuParams = reactive<Spu>({
  category3Id: '', //收集三级分类的ID
  spuName: '', //SPU的名字
  description: '', //SPU的描述
  tmId: '', //品牌的ID
  spuImageList: [],
  spuSaleAttrList: [],
})
async function initHasSpu(spu: Spu) {
  spuParams = Object.assign(spuParams, spu)
  let res: AllTradeMark = await reqAllTradeMark()
  let res1: SpuHasImg = await reqSpuImageList(spu.id as number)
  let res2: SaleAttrResponseData = await reqSpuHasSaleAttr(spu.id as number)
  let res3: HasSaleAttrResponseData = await reqAllSaleAttr()

  allTradeMark.value = res.data
  imgList.value = res1.data.map((item) => {
    return {
      name: item.imgName,
      url: item.imgUrl,
    }
  })
  saleAttr.value = res2.data
  allSaleAttr.value = res3.data
}

async function initAddSpu(c3Id: number | string) {
  Object.assign(spuParams, {
    category3Id: c3Id, //收集三级分类的ID
    spuName: '', //SPU的名字
    description: '', //SPU的描述
    tmId: '', //品牌的ID
    spuImageList: [],
    spuSaleAttrList: [],
  })
  //清空照片
  imgList.value = []
  //清空销售属性
  saleAttr.value = []
  saleAttrIdAndValueName.value = ''
  let res: AllTradeMark = await reqAllTradeMark()
  let res1: HasSaleAttrResponseData = await reqAllSaleAttr()
  allTradeMark.value = res.data
  allSaleAttr.value = res1.data
}
function handlePictureCardPreview(file: any) {
  dialogVisible.value = true
  dialogImageUrl.value = file.url
  console.log(file)
}

function handleRemove(file: any, fileList: any) {
  console.log(file, fileList)
}

const handlerUpload = (rawFile: any) => {
  if (
    rawFile.type !== 'image/jpeg' &&
    rawFile.type !== 'image/png' &&
    rawFile.type !== 'image/gif'
  ) {
    ElMessage.error('上传格式务必是jpg/png/gif格式')
    return false
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('图片大小不能超过2MB！')
    return false
  }
  return true
}

// 计算当前未拥有的销售属性
let unSelectSaleAttr = computed(() => {
  let unSelectAttr = allSaleAttr.value.filter((item) => {
    return saleAttr.value.every((item1) => {
      return item1.saleAttrName != item.name
    })
  })
  return unSelectAttr
})

function addSaleAttr() {
  const [baseSaleAttrId, saleAttrName] = saleAttrIdAndValueName.value.split(':')
  let newSaleAttr: SaleAttr = {
    baseSaleAttrId,
    saleAttrName,
    spuSaleAttrValueList: [],
  }

  saleAttr.value.push(newSaleAttr)
  saleAttrIdAndValueName.value = ''
}

function toLook(row: SaleAttr) {
  const { baseSaleAttrId, saleAttrValue } = row
  let newSaleAttrValue: SaleAttrValue = {
    baseSaleAttrId,
    saleAttrValueName: saleAttrValue as string,
  }
  let repeat = row.spuSaleAttrValueList.find((item) => {
    return item.saleAttrValueName == saleAttrValue
  })
  if (repeat) {
    ElMessage.warning('该属性值已存在')
    return
  }
  if (saleAttrValue?.trim() == '') {
    ElMessage.error('属性值不能为空')
    return
  }

  row.spuSaleAttrValueList.push(newSaleAttrValue)

  row.flag = false
}

function toEdit(row: SaleAttr) {
  row.flag = true
  row.saleAttrValue = ''
  saleAttrIdAndValueName.value = ''
}

async function save() {
  spuParams.spuImageList = imgList.value.map((item: any) => {
    return {
      imgName: item.name,
      imgUrl: (item.response && item.response.data) || item.url,
    }
  })
  spuParams.spuSaleAttrList = saleAttr.value

  let res = await reqAddOrUpdateSpu(spuParams)
  if (res.code == 200) {
    ElMessage.success(spuParams.id ? '修改成功' : '添加成功')
  } else {
    ElMessage.error(spuParams.id ? '修改失败' : '修改失败')
  }
  $emit('changeScene', 0)
}

defineExpose({ initHasSpu, initAddSpu })
</script>

<style scoped lang="scss">
:deep(.el-select) {
  width: 160px;
}
</style>
